<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\DeptRequest;
use App\Models\SysDept;
use App\Models\SysRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SysDeptController extends ApiBaseController
{
    public function index(Request $request){
        $items = SysDept::filter($request->all())->get();
        return success([
            'rows' => $items
        ]);
    }

    public function show(Request $request, SysDept $model){
        $id = $request->get('id');
        $data = $model->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function create(DeptRequest $request){
        $params = $request->all();
        if($params['parent_id'] > 0){
            //获取所有数据并检索

        }
        $model = SysDept::create($request->all());
        return success([],'添加成功');
    }

    public function update(DeptRequest $request, SysDept $model)
    {
        $id = $request->post('id');
        $dept = $model->find($id);
        $validated = $request->validated();

        if($dept){
            $dept->update($request->all());
        }else{
            return error('数据不存在');
        }

        return success([],'更新成功');
    }

    public function destroy($ids, Request $request, SysDept $model){
        $id_arr = explode(',', $ids);
        $model->destroy($id_arr);
    }

    public function deptTreeSelect(){
        $items = SysDept::getMenuTree();
        $data = makeTree($items->toArray(),'id', 'parent_id');
        return success(['data' => $data]);
    }

    public function roleDeptTreeselect($role_id){
        $items = SysDept::getMenuTree();
        $depts = makeTree($items->toArray(),'id', 'parent_id');
        $checkedKeys = DB::table('sys_role_dept')->where('role_id', $role_id)->pluck('dept_id');

        $role = SysRole::where('id', $role_id)->first();
        if($role['dept_check_strictly'] == true){
            $checkedItems = SysDept::whereIn('id',$checkedKeys)->select('id','parent_id', 'dept_name')->get();
            $checkedItems_tree = makeTree($checkedItems->toArray(),'id', 'parent_id');
            $checkedKeys = [];
            get_last_node($checkedItems_tree,$checkedKeys);
        }

        return success([
            'depts' => $depts,
            'checkedKeys' => $checkedKeys
        ]);
    }

}
